<?php

namespace App\Http\Middleware\Management;

use App\Utils\JWTHelper\JWTHelper;
use App\Utils\ResponseResult\JsonResult;
use Closure;
use \Ramsey\Uuid\Uuid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;

class ArticleController
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function list(Request $request)
    {
        $title = $request->input('title') ?? "";
        $author = $request->input('author') ?? "";
        $status = $request->input('status') ?? -1;
        $beginAt = $request->input('begin_at') ?? "";
        $endAt = $request->input('end_at') ?? "";
        $per_page = $request->input('per_page',env('DEFAULT_PAGE'));

        // 添加排序参数
        $orderField = $request->input('order_field', 'id');  // 默认按id排序
        $orderType = $request->input('order_type', 'desc');  // 默认降序

        // 验证排序字段是否合法
        $allowedOrderFields = ['id', 'created_at', 'title', 'status'];
        if (!in_array($orderField, $allowedOrderFields)) {
            $orderField = 'id';
        }

        // 验证排序类型是否合法
        $orderType = strtolower($orderType) === 'asc' ? 'asc' : 'desc';

        $list = DB::table("articles as a")
            ->join("users as u","a.author_id","=","u.id")
            ->where(function($query) use ($title,$author,$status,$beginAt,$endAt){
                if ($title!=""){
                    $query->where("a.title","like","%".$title."%");
                }
                if ($author!=""){
                    $query->where("a.author","like","%".$author."%");
                }
                if($status!=-1){
                    $query->where("a.status",$status);
                }
                if ($beginAt!==""){
                    $query->whereDate("a.created_at",">=".$beginAt);
                }
                if ($endAt!==""){
                    $query->whereDate("a.created_at","<=".$endAt);
                }
            })
            ->select("a.*","u.name as author")
            ->orderBy("a." . $orderField, $orderType)  // 添加排序
            ->paginate($per_page)
            ->withQueryString();

        return JsonResult::success($list,"查询文章成功");
    }
    public function create(Request $request){
        //验证请求
        $rules=[
            "title" => "required",
        ];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //创建
        $data=$request->all();
        $jwtToken=$request->header('Authorization');
        $data["author_id"]=JWTHelper::getCustom($jwtToken)->id;
        $insertCount=DB::table("articles")->insertGetId($data);
        if($insertCount>0){
            return JsonResult::success(null,"创建文章成功");
        }
        return JsonResult::forbidden(null,"创建文章失败");
    }
    public function edit(Request $request){
        //验证请求
        $rules=[
            "id" => "required",
            "title" => "nullable|max:100",
            "status" => "nullable|in:0,1"
        ];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        $id=$request->input("id");
        $data=$request->only("title","content","status");
        //验证更新数据
        if (count($data)==0){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //更新数据
        DB::table("articles")
            ->where("id",$id)
            ->update($data);
        return JsonResult::success(null,"修改文章成功");
    }
    public function delete(Request $request){
        //验证请求
        $rules=[
            "id" => "required"
        ];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        $ids=$request->input("id");
        $idsArr=explode(",",$ids);
        //删除数据
        foreach ($idsArr as $id){
            // 检查文章状态
            $article = DB::table("articles")->where("id", $id)->first();
            if (!$article) {
                return JsonResult::forbidden(null, "文章不存在");
            }
            if ($article->status == 1) {
                return JsonResult::forbidden(null, "文章已发布，无法删除");
            }
            // 执行删除
            DB::table("articles")
                ->where("id", $id)
                ->delete();
        }
        return JsonResult::success(null,"删除文章成功");
    }

    public function upload(Request $request){
        $rules=[
            'file' => 'required|mimes:jpg,png,jpeg,gif,pdf,doc,docx,xls,xlsx,zip,rar|max:10240',
        ];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        try {
            //处理文件上传逻辑
            $file=$request->file("file");
            //保存文件到指定目录
            $destinationPath="uploads";
            //构成新的文件名
            $filename=Uuid::uuid4().'.'.$file->getClientOriginalExtension();
            //移动文件到指定目录
            $file->move($destinationPath,$filename);
            return JsonResult::success($filename,"文件上传成功");
        }catch (\Exception $e){
            return JsonResult::forBidden($filename,"文件上传失败");
        }
    }
}
